<?php
namespace App\Service\Admin\Qudao;

use App\Service\Admin\BaseService as Service;

class OrderService extends Service
{
    //订单

    protected $statuss = [
        1 => '未付款', '未发货', '未收货', '已完成',
    ];

    /**
     * 列表
     * @param array $pas【status：1未付款，2审核中，3未发货；keyword：搜索词】
     * @param array $pages【start，limit】
     */
    public function getList($pages, $pas)
    {
        (new \App\Service\ApiQd\OrderService())->autoAccept(5); //自动收货
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->db2Conn($this->dbQdOrder)->where('del', 0);
        $status = $pas['status'];
        $orderno = $pas['orderno'];
        $phone = $pas['phone'];
        $ws = [];
        if ($status == 1) {
            $ws[] = ['iscancel', '=', 1];
            $ws[] = ['status', '=', 1];
            $db = $db->where($ws);
        } else if ($status == 2) {
            $ws[] = ['iscancel', '=', 2];
            $db = $db->where($ws);
        } else if ($status == 3) {
            $ws[] = ['iscancel', '=', 1];
            $ws[] = ['delivery', '=', 1];
            $ws[] = ['status', '=', 2];
            $db = $db->where($ws);
        } else {
        }
        if ($orderno) {
            $db = $db->where('orderno', 'like', '%'.$orderno.'%');
        }
//        if ($phone) { //渠道商手机号
//            $uids = [];
//            $uOnes = $this->dbwbConn($this->dbQdShop)->where('phone', 'like', '%'.$phone.'%')->get();
//            if (count($uOnes)) {
//                foreach ($uOnes as $v) {
//                    $uids[] = $v->id;
//                }
//            }
//            $db = $db->whereIn('uid', $uids);
//        }
        if ($phone) { //收件人
            $addressIds = [];
            $uOnes = $this->dbwbConn($this->dbQdAddress)->where('phone', 'like', '%'.$phone.'%')->get();
            if (count($uOnes)) {
                foreach ($uOnes as $v) {
                    $addressIds[] = $v->id;
                }
            }
            $db = $db->whereIn('address_id', $addressIds);
        }
        if ($pas['start_day']) {
            $startDay = $pas['start_day'].' 00:00:01';
            $db = $db->where('addtime', '>=', $startDay);
        }
        if ($pas['end_day']) {
            $endDay = $pas['end_day'].' 23:59:59';
            $db = $db->where('addtime', '<=', $endDay);
        }
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $statuss = $this->statuss;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //商家信息
            $uOne = (array) $this->db2Conn($this->dbQdShop)->where('id', $v['uid'])->first();
            $phone = empty($uOne) ? '-' : $uOne['phone'];
            //SKU信息
            $skuOnes = $this->db2Conn($this->dbQdOsku)->where('order_id', $v['id'])->get();
            $ginfo = '';
            if (count($skuOnes)) {
                foreach ($skuOnes as $vv) {
                    $vv = (array) $vv;
                    $ginfo .= '商品名称：'.$vv['gname'].'<br/>';
                    $ginfo .= 'Sku名称：'.$vv['sku_name'].'<br/>';
                    $imgPrefix = file_exists($vv['gimg']) ? env('DOMAIN').'/' : env('FC_DOMAIN').'/';
                    $ginfo .= '商品图片：<img src="'.$imgPrefix.$vv['gimg'].'" height="50"/>'.'<br/>';
                    $ginfo .= '商品单价：'.$vv['price']/100 . '<br/>'.'<br/>';
                    $ginfo .= '商品数量：'.$vv['num'] . '<br/>'.'<br/>';
                }
            }
            $status_name = array_key_exists($v['status'], $statuss) ? $statuss[$v['status']] : '';
            $acceptOne = (array) $this->db2Conn($this->dbQdAddress)
                ->where('id', $v['address_id'])
                ->first();
            $accepter = empty($acceptOne) ? '-' : $acceptOne['accepter'];
            $accept_address = empty($acceptOne) ? '-' : $acceptOne['wx_door'];
            $arys[] = [
                'id' => $v['id'],
                'orderno' => $v['orderno'],
                'uname' => $v['uname'],
                'phone' => $phone,
                'ginfo' => $ginfo,
                'price' => toNumber($v['price']),
                'accepter' => $accepter,
                'accept_address' => $accept_address,
                'status' => $v['status'],
                'status_name' => $status_name,
                'addtime' => $v['addtime'],
                'iscancel' => $v['iscancel'],
                'wuliu' => $v['wuliuhao'],
                'wuliuhao' => $v['wuliuhao'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 列表
     */
    public function getOlist()
    {
        $db = $this->db2Conn($this->dbQdOrder)->where('del', 0);
        $res = $db->get();
        if (!count($res)) {
            return $this->toback(-2, '没有分类');
        }
        $statuss = $this->statuss;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $skuOnes = $this->db2Conn($this->dbQdOsku)->where('order_id', $v['id'])->get();
            $ginfo = '';
            if (count($skuOnes)) {
                foreach ($skuOnes as $vv) {
                    $vv = (array) $vv;
                    $ginfo .= '商品名称：'.$vv['gname'];
                    $ginfo .= 'Sku名称：'.$vv['sku_name'];
                    $ginfo .= '商品单价：'.$vv['price']/100;
                    $ginfo .= '商品数量：'.$vv['num'];
                    $ginfo .= '；';
                }
            }
            $status_name = array_key_exists($v['status'], $statuss) ? $statuss[$v['status']] : '';
            $acceptOne = (array) $this->db2Conn($this->dbQdAddress)
                ->where('uid', $v['uid'])
                ->where('selected', 1)
                ->first();
            $accepter = empty($acceptOne) ? '-' : $acceptOne['accepter'];
            $accept_address = empty($acceptOne) ? '-' : $acceptOne['wx_door'];
            $arys[] = [
                'id' => $v['id'],
                'orderno' => $v['orderno'],
                'uname' => $v['uname'],
                'ginfo' => $ginfo,
                'price' => toNumber($v['price']),
                'accepter' => $accepter,
                'accept_address' => $accept_address,
                'status_name' => $status_name,
            ];
        }
        return $this->toback(0, '', $arys);
    }

    /**
     * 购物车列表
     * @param array $pages【start，limit】
     */
    public function cartList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->db2Conn($this->dbQdCart)->where('del', 0);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有分类');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            if (file_exists($v['gimg'])) {
                $imgPrefix = env('DOMAIN') . '/';
            } else {
                $imgPrefix = env('FC_DOMAIN') . '/';
            }
            $uOne = (array) $this->dbwbConn($this->dbQdShop)
                ->where('id', $v['uid'])
                ->first();
            $skuOne = (array) $this->dbwbConn($this->dbQdGsku)
                ->where('gid', $v['gid'])
                ->orderBy('price', 'asc')
                ->first();
            $price = 0;
            if (!empty($uOne) && !empty($skuOne)) {
                $price = $uOne['level']==1 ? $skuOne['price_one'] : $skuOne['price_two'];
            }
            $arys[] = [
                'id' => $v['id'],
                'uname' => $v['uname'],
                'gname' => $v['gname'],
                'imgPrefix' => $imgPrefix,
                'imgLink' => $v['gimg'],
                'sku_name' => $v['sku_name'],
                'price' => toNumber($price),
                'num' => $v['num'],
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 收货地址列表
     */
    public function acceptList()
    {
        $db = $this->db2Conn($this->dbQdAddress)->where('del', 0);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uOne = (array) $this->db2Conn($this->dbQdShop)->where('id', $v['uid'])->first();
            $uname = empty($uOne) ? '-' : $uOne['nickname'];
            $arys[] = [
                'id' => $v['id'],
                'uname' => $uname,
                'accepter' => $v['accepter'],
                'phone' => $v['phone'],
                'wx_name' => $v['wx_name'],
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 订单详情
     * @param int $id
     */
    public function getOne($id)
    {
        $res = (array) $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '订单不存在');
        }
        $status1s = $this->orderStatus1s;
        $status2s = $this->orderStatus2s;
        $cancels = $this->orderCancels;
        $deliverys = $this->orderDeliverys;
        //SKU信息
        $skuOnes = $this->dbwbConn($this->dbQdOsku)->where('order_id', $res['id'])->get();
        $sku_name = '-';
        $gname = '-';
        $gimg = '';
        $num = 0;
        if (count($skuOnes)) {
            $skuOne = (array) $skuOnes[0];
            $sku_name = $skuOne['sku_name'];
            $gname = $gname!='-' ? $gname : $skuOne['gname'];
            foreach ($skuOnes as $skuOne) {
                $skuOne = (array) $skuOne;
                $num += $skuOne['num'];
            }
        }
        $res['price'] = $res['price'] / 100;
        $res['real_pay'] = $res['real_pay'] / 100;
        $res['cancel_name'] = array_key_exists($res['iscancel'], $cancels) ? $cancels[$res['iscancel']] : '-';
        if ($res['iscancel'] > 1) {
            $res['status_name'] = array_key_exists($res['iscancel'], $cancels) ? $cancels[$res['iscancel']] : '';
        } else if ($res['delivery'] == 1) {
            $res['status_name'] = array_key_exists($res['status'], $status1s) ? $status1s[$res['status']] : '';
        } else {
            $res['status_name'] = array_key_exists($res['status'], $status2s) ? $status2s[$res['status']] : '';
        }
        $res['sku_name'] = $sku_name;
        $res['gname'] = $gname;
        $res['gimg'] = $gimg;
        $res['num'] = $num;
        $res['deliveryName'] = array_key_exists($res['delivery'], $deliverys) ? $deliverys[$res['delivery']] : '';
        //收货地址
        $addressOne = (array) $this->dbwbConn($this->dbQdAddress)->where('id', $res['address_id'])->first();
        $res['accepter'] = empty($addressOne) ? '' : $addressOne['accepter'];
        $res['acceptName'] = empty($addressOne) ? '' : $addressOne['wx_door'];
        $res['acceptPhone'] = empty($addressOne) ? '' : $addressOne['phone'];
//        //优惠劵
//        $couponOne = (array) $this->dbwbConn($this->dbUcoupon)->where('id', $res['coupon_id'])->first();
//        $res['quata'] = empty($couponOne) ? 0 : $couponOne['quata'];
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    //订单审核
    public function setAuth($id, $status)
    {
        $res = (array) $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['iscancel'] == 3) {
            return array('code' => -2, 'msg' => '该订单已通过审核');
        }
        $cancel = $status==1 ? 1 : 3;
        $up = $this->dbwbConn($this->dbQdOrder)
            ->where('id', $id)
            ->update(['iscancel' => $cancel, 'cancelauthtime' => toDate()]);
        if (!$up) {
            return array('code' => -1, 'msg' => 'error');
        }
//        //看看有没有优惠劵，待付款的可退还
//        if ($res['status'] >= 2 && $res['coupon_id']) {
//            $this->dbModify($this->dbOrder, ['id'=>$id], ['coupon_id'=>0]);
//            $this->dbModify($this->dbUcoupon, ['id'=>$res['coupon_id']], ['status'=>2]);
//        }
        $resData = [
            'uid' => $res['uid'],
            'orderno' => $res['orderno'],
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $resData);
    }

    /**
     * 订单发货
     * @param array $ids
     * @param array $pas
     */
    public function send($ids, $pas)
    {
        $res = $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->whereIn('id', $ids)
            ->where('iscancel', 1)
            ->where('delivery', 1)
            ->where('status', 2)
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '该订单不存在或状态错误');
        }
        $up = $this->dbwbConn($this->dbQdOrder)->whereIn('id', $ids)
            ->update([
                'wuliu' => $pas['wuliu'], 'wuliuhao' => $pas['wuliuhao'],
                'status' => 3, 'sendtime' => toDate(),
            ]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     *批量发货
     * @param array $os
     */
    public function batchSend($os)
    {
        foreach ($os as $o) {
            $id = $o['id'];
            $orderno = $o['orderno'];
            $wuliu = $o['wuliu'];
            $wuliuhao = $o['wuliuhao'];
            $res = (array) $this->dbwbConn($this->dbQdOrder)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($res)) {
                return $this->toback(-2, $orderno.'订单不存在');
            }
            if ($res['iscancel'] != 1) {
                return array('code' => -2, 'msg' => $orderno.'订单非正常状态');
            }
            if ($res['delivery'] != 1) {
                return array('code' => -2, 'msg' => $orderno.'订单属于自提');
            }
            if ($res['status'] != 2) {
                return array('code' => -2, 'msg' => $orderno.'订单状态错误');
            }
            $up = $this->dbwbConn($this->dbQdOrder)->where('id', $id)
                ->update([
                    'wuliu' => $wuliu, 'wuliuhao' => $wuliuhao,
                    'status' => 3, 'sendtime' => toDate(),
                ]);
            if (!$up) {
                return $this->toback(-1, $orderno.'错误');
            }
        }
        return $this->toback();
    }

//    /**
//     * 订单发货
//     * @param array $id
//     * @param array $pas
//     */
//    public function send($id, $pas)
//    {
//        $res = (array) $this->dbwbConn($this->dbQdOrder)
//            ->where('del', 0)
//            ->where('id', $id)
//            ->first();
//        if (empty($res)) {
//            return array('code' => -2, 'msg' => '该订单不存在');
//        }
//        if ($res['iscancel'] != 1) {
//            return array('code' => -2, 'msg' => '该订单非正常状态');
//        }
//        if ($res['delivery'] != 1) {
//            return array('code' => -2, 'msg' => '该订单属于自提');
//        }
//        if ($res['status'] != 2) {
//            return array('code' => -2, 'msg' => '该订单状态错误');
//        }
//        $up = $this->dbwbConn($this->dbQdOrder)
//            ->where('id', $id)
//            ->update([
//                'wuliu' => $pas['wuliu'], 'wuliuhao' => $pas['wuliuhao'],
//                'status' => 3, 'sendtime' => toDate(),
//            ]);
//        if (!$up) {
//            return array('code' => -1, 'msg' => 'error');
//        }
//        return array('code' => 0, 'msg' => 'success');
//    }
}